from django.shortcuts import render,redirect,reverse
import json,re
from django.conf import settings
from .models import *
from django.contrib.auth import authenticate,login
from django.http import HttpResponse
from geetest import GeetestLib
from django.shortcuts import render
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from django.core.mail import send_mail
from django.views import View
from django.core.cache import cache
from utils import aliyun,restful
from django.core.paginator import PageNotAnInteger,Paginator,EmptyPage



#请在官网申请ID使用，示例ID不可使用
pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"
mobile_geetest_id = "7c25da6fe21944cfe507d2f9876775a9"
mobile_geetest_key = "f5883f4ee3bd4fa8caec67941de1b903"


#注册
def reg(request):
    if request.method=='POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        cpassword = request.POST.get('cpassword')
        email = request.POST.get('email')
        yzm = request.POST.get('yzm')
        t1 = request.POST.get('t1')
        if not all([username,password,cpassword,email]):
            print(t1)
            return render(request,'reg.html',{'err':'数据不完整'})
        if password != cpassword:
            return render(request,'reg.html',{'err':'两次密码不一致'})
        if authenticate(username=username):
            return render(request,'reg.html',{'err':'该用户已存在'})
        if not re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$", email):
            return render(request,"reg.html", { "err": "邮箱格式不正确"})
        if yzm == 'no':
            return render(request, 'reg.html', {'err': '请滑动验证码'})
        else:
            if t1 != None:
                user =User.objects.create_user(username=username,password=password,email=email,quanxian=1)
                user.is_active = 0
                user.save()
                # 加密用户id，生成激活的token
                serializer = Serializer(settings.SECRET_KEY, 3600)
                info = {"confirm": user.id}
                token = serializer.dumps(info).decode()
                subject = "学生管理系统欢迎你"  # 邮件标题
                message = ''  # 邮件正文
                sender = settings.EMAIL_FROM  # 发件人
                receiver = [email]  # 收件人
                html_message = """
                         <h1>%s  恭喜您成为学生管理系统的注册会员</h1><br/><h3>请您在1小时内点击以下链接进行账户激活</h3>
                         <a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>
                         """ % (username, token, token)
                send_mail(subject, message, sender, receiver, html_message=html_message)
                return redirect(reverse("login"))
            else:
                user = User.objects.create_user(username=username, password=password, email=email, quanxian=0)
                user.is_active = 0
                user.save()
                # 加密用户id，生成激活的token
                serializer = Serializer(settings.SECRET_KEY, 3600)
                info = {"confirm": user.id}
                token = serializer.dumps(info).decode()
                subject = "学生管理系统欢迎你"  # 邮件标题
                message = ''  # 邮件正文
                sender = settings.EMAIL_FROM  # 发件人
                receiver = [email]  # 收件人
                html_message = """
                         <h1>%s  恭喜您成为学生管理系统的注册会员</h1><br/><h3>请您在1小时内点击以下链接进行账户激活</h3>
                         <a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>
                         """ % (username, token, token)
                send_mail(subject, message, sender, receiver, html_message=html_message)
                return redirect(reverse("login"))

            # return render(request,'reg.html',{'err':'注册成功！'})
    else:
        return render(request,'reg.html')

#用户激活
class ActiveView(View):
    def get(self,requset,token):
        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            info = serializer.loads(token)
            user_id = info['confirm']
            user = User.objects.get(id=user_id)
            user.is_active = 1
            user.save()
            return redirect(reverse('login'))
        except SignatureExpired as e:
            return HttpResponse('您的激活码已经过期')



def userlogin(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if not all([username,password]):
            return render(request,'login.html',{'err':'请填写完整数据'})
        user = authenticate(username=username,password=password)
        if user is not None:
            if user.is_active:
                login(request,user)
                request.session['username']=username
                response = redirect(reverse('index'))
                remember = request.POST.get('remember')
                if remember == 'on':
                    response.set_cookie("username", username, max_age=7 * 24 * 3600)
                else:
                    response.delete_cookie("username")
                return response
            else:
                return render(request, 'login.html', {'err': '用户未激活'})
        else:
            return render(request,'login.html',{'err':'用户或密码错误'})
    else:
        return render(request,'login.html')

#主页
def index(request):
    user = request.user.id
    name = User.objects.filter(id=user)
    quanxian = name[0].quanxian
    print(quanxian)
    return render(request,'index.html',{'qx':quanxian})


#滑动验证码
def pcgetcaptcha(request):
    user_id = 'test'
    gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    status = gt.pre_process(user_id)
    request.session[gt.GT_STATUS_SESSION_KEY] = status
    request.session["user_id"] = user_id
    response_str = gt.get_response_str()
    return HttpResponse(response_str)
def pcvalidate(request):
    if request.method == "POST":
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')
        validate = request.POST.get(gt.FN_VALIDATE, '')
        seccode = request.POST.get(gt.FN_SECCODE, '')
        status = request.session[gt.GT_STATUS_SESSION_KEY]
        user_id = request.session["user_id"]
        if status:
            result = gt.success_validate(challenge, validate, seccode, user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        result = "<html><body><h1>登录成功</h1></body></html>" if result else "<html><body><h1>登录失败</h1></body></html>"
        return HttpResponse(result)
    return HttpResponse("error")


#短信下发
def test_redis(requset):
    #存储数据
    cache.set('name', 'tom', 20)  # 该值的有效期为20s
    # 判断Redis中是否存在
    print(cache.has_kay("name")) #包含:true
    #  获取
    print(cache.get("name")) #返回:tom 无返回Null
    return HttpResponse("测试Redis")

def send_sms(request):
    #接口地址:/duanxin/send_sms/?phone=xxxx
    # 1 获取手机
    phone = request.GET.get('phone')
    print('手机:'+phone)
    # 2 生成6位随机码
    code = aliyun.get_code(6, False)
    # 3 缓存到redis
    cache.set(phone,code,30*60)#60s有效
    print('是否写入redis成功:',cache.has_key(phone))
    print('打印code:',cache.get(phone))
    # 4 发短信
    result =aliyun.send_sms(phone, code)
    return HttpResponse(result)

def  check_sms(request):
    #/duanxin/check_sms/?phone=xxx&code=xx
    # 1 后去电话和code
    phone = request.GET.get('phone')
    code = request.GET.get('code')
    # 2 获取Resis中code
    cache_code = cache.get(phone)
    # 3 判断
    if code == cache_code:
        return  restful.ok("OK", data=None)
    else:
        return restful.page_error("False", data=None)


#个人信息
def ginfo(request):
    user = request.user.id
    use = User.objects.filter(pk=user)
    print(use)
    xuesheng = Info.objects.filter(user_id=use[0].id)
    print(xuesheng)
    if xuesheng:
        xinfo = xuesheng[0]
        return render(request,'info.html',{'info':xinfo.name,'age':xinfo.age,'xueli':xinfo.xueli,'jieguo':xinfo.jieguo,'jianjie':xinfo.jianjie,'fx':xinfo.fangxiang,'img':xinfo.img.url})
    else:
        return render(request, 'info.html', {'err':'没有绑定信息'})
#全部信息
def allinfo(request):
    user = request.user.id
    name = User.objects.filter(id=user)
    quanxian = name[0].quanxian
    al = Info.objects.all()
    fy = Paginator(al,10)
    try:
        number= request.GET.get('index','1')
        num = fy.page(number)
    except PageNotAnInteger:
        num = fy.page(1)
    except EmptyPage:
        num = fy.page(fy.num_pages)
    return render(request,'allinfo.html',{'num':num,'page':fy,'count':len(al),'qx':quanxian})


#修改信息
def data(request):
    user = request.user.id
    if request.method=='POST':
        nname = request.POST.get('dname')
        nage = request.POST.get('dage')
        nxueli = request.POST.get('dxueli')
        nfangxiang = request.POST.get('dfangxiang')
        if nname:
            Info.objects.filter(user_id=user).update(name=nname)
        if nage:
            Info.objects.filter(user_id=user).update(age=nage)
        if nxueli:
            Info.objects.filter(user_id=user).update(xueli=nxueli)
        if nfangxiang:
            Info.objects.filter(user_id=user).update(fangxiang=nfangxiang)
            return render(request,'data.html',{'err':'修改成功'})
        else:
            return render(request,'data.html')
    else:
        return render(request,'data.html')

#查看自己的任务
def task(request):
    user = request.user.id
    use = Info.objects.filter(user_id=user)
    if use:
        user1 = use[0].id
        user2 = use[0]
        x = InfoCon.objects.filter(info_id=user1)
        info = [Con.objects.get(id=a.con_id) for a in x ]
        print(info)
        return render(request,'task.html',{'err':info})
    else:
        return render(request, 'task.html', {'con': '暂没有任务'})


#添加任务
def addtask(request):
    if request.method == 'POST':
        renwu1 = request.POST.get('renwu')
        if renwu1:
            Con.objects.create(con=renwu1)
            return render(request,'addtask.html',{'err':'添加任务成功'})
        else:
            return render(request,'addtask.html',{'err':'添加任务失败'})

    else:
        return render(request,'addtask.html')
#指定学生添加任务
def xz(request):
    all1 = Info.objects.all()
    if request.method == 'POST':
        wenben = request.POST.get('renwu1')
        xs = request.POST.getlist('xs')
        print(xs)
        if wenben and xs:
            con1 = Con.objects.create(con=wenben)
            for a in xs :
                print(a)
                InfoCon.objects.create(info_id=a,con_id=con1.id,wcd=0)
            return render(request,'xz.html',{'err':'添加任务成功','info':all1})
        else:
            return render(request, 'xz.html', {'err': '添加任务失败','info':all1})
    else:
        return render(request,'xz.html',{'info':all1})


#全部任务
def alltask(request):
    allr = Con.objects.all()

    return render(request,'alltask.html',{'con':allr})


def user_img(request):
    if request.method =='POST':
        user_file = request.FILES.get('user_file')
        user_i = request.user.id
        user_m = Info.objects.get(user_id=user_i)
        user_m.img = user_file
        user_m.save()
        return redirect(reverse('index'))
    else:
        return render(request,'info.html')

#修改学生信息
def lsupdate(request):
    all1 = Info.objects.all()
    if request.method == 'POST':
        student = request.POST.getlist('xs')
        sname = request.POST.get('dname')
        sage = request.POST.get('dage')
        sxueli = request.POST.get('dxueli')
        sfx = request.POST.get('dfangxiang')
        spy = request.POST.get('pingyu')
        print([sname,sage,sxueli,sfx,spy])
        print(any([sname,sage,sxueli,sfx,spy]))
        if student:
            for a in student:
                info = Info.objects.filter(id=a)
                if not any([sname,sage,sxueli,sfx,spy]):
                    print('1')
                    return render(request,'lsupdate.html',{ 'err': '修改失败','all': all1})
                elif sname:
                    info.update(name=sname)
                elif sage:
                    info.update(age=sage)
                elif sxueli:
                    info.update(xueli=sxueli)
                elif sfx:
                    info.update(fangxiang=sfx)
                elif spy:
                    info.update(jianjie=spy)
                return render(request,'lsupdate.html', { 'err': '修改成功','all': all1})

        else:
            return render(request, 'lsupdate.html', {'err': '请选择学生','all':all1})
    else:
        return render(request,'lsupdate.html',{'all':all1})

#完成情况
def wcqk(request):
    # all2 = InfoCon.objects.all()
    all1 = Info.objects.all()
    dic ={}
    for x in all1:
        len_task = InfoCon.objects.filter(info_id=x.id)
        len_task1 = InfoCon.objects.filter(info_id=x.id,wcd=1)
        dic[x.name] = [len(len_task1),len(len_task)]
    return render(request,'wcqk.html',{'dic':dic})



def response_as_json(data):
    json_str = json.dumps(data)
    response = HttpResponse(
        json_str,
        content_type="application/json",
    )
    response["Access-Control-Allow-Origin"] = "*"
    return response


def json_response(data, code=200):
    data = {
        "code": code,
        "msg": "success",
        "data": data,
    }
    return response_as_json(data)


    data.update(kwargs)
def json_error(error_string="error", code=500, **kwargs):
    data = {
        "code": code,
        "msg": error_string,
        "data": {}
    }
    return response_as_json(data)


JsonResponse = json_response
JsonError = json_error



import pandas as pd
from pyecharts.charts import Bar
from pyecharts import options as opts
import json,sqlite3

from pyecharts import options as opts
from pyecharts.charts import Page, Pie

class PieView(View):
    def get(self,request):
        conn = Info.objects.all()
        li = []
        l2 = []
        l3 = []
        for i in conn:

            li.append(i.id)
            l2.append(i.rw)
            for i in zip(l2,li):
                l3.append(i)

        pie = Pie()
        pie.add("完成比例",l3)
        pie.set_global_opts(title_opts=opts.TitleOpts(title="完成占比"))
        pie.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        options = pie.dump_options()
        return JsonResponse(json.loads(options))

class Bili_pieView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse(content=open("./templates/pie.html").read())




class BarView(View):
    def get(self,request):
        bar = Bar()
        stdli = []
        stdzuoye = []
        stdall = Info.objects.all()
        for i in stdall:
            stdli.append(i.name)
            x = InfoCon.objects.filter(info_id=i.pk,wcd=1)
            stdzuoye.append(len(x))
            # for x in stdall1:
            #     stdli.append(x.name)
            #     stdhomekork = InfoCon.objects.filter(info_id=x.pk,wcd=1)
            #     stdzuoye.append(len(stdhomekork))
        bar.add_xaxis(stdli)
        bar.add_yaxis('完成数量',stdzuoye)
        bar.set_global_opts(title_opts=opts.TitleOpts(title='学生作业完成情况', subtitle=''))
        options = bar.dump_options()
        return JsonResponse(json.loads(options))


